//
//  MyTeamVC.swift
//  LeGou
//
//  Created by lxm on 2022/7/30.
//

import UIKit

class MyFansVC: ZMViewController {
    //MARK: --------------------属性--------------------
    let myTeamInfo = ZMUtil.fastNilBehavior(type: MineModels.TeamAcModel.self)
    
    var recommendWxStr = ""
    
    var wechateCode = ""
    //MARK: --------------------UI控件-------------------
    @IBOutlet weak var mainScroll: UIScrollView!
    @IBOutlet weak var stack: UIStackView!
        
    @IBOutlet weak var direct: UILabel!
    
    @IBOutlet weak var indirect: UILabel!
    
    let loading = XMLoadingView()
    
    @IBOutlet weak var treeView: MyTeamUserTreeView!
    
    @IBOutlet weak var img: UIImageView!
    
    @IBOutlet weak var codeImg: UIImageView!
    
    @IBOutlet weak var recommendName: UILabel!
    
    @IBOutlet weak var recommendWx: UILabel!
    
    @IBOutlet weak var copyButton: UIButton!
    
    @IBOutlet weak var gpcy: UILabel!
    
    
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loadMyTeamInfo()
        loadMyRecommendInfo()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        glt_scrollView = mainScroll
        title = "我的粉丝"
        let tap = UITapGestureRecognizer()
        codeImg.addGestureRecognizer(tap)
        tap.addTarget(self, action: #selector(onCodeTap))
        codeImg.isUserInteractionEnabled = true
        gpcy.isHidden = true
    }
    
    func addConstraints() {
        
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        myTeamInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            self.direct.text = "\(resp.currentUser.inviteNum)"
            self.indirect.text = "\(resp.currentUser.inDirectNum)"
            self.treeView.isHidden = true
//            self.treeView.me.zm.setImage(urlStr: resp.currentUser.avatar, placeholder: "def_user_img")
//            self.treeView.vip.isHidden = resp.currentUser.serviceProviderLevel == 0
            
//            for i in 0 ..< resp.nodes.count {
//                let node = resp.nodes[i]
//                let userView = self.treeView.subarray[i]
//                if let u = node.user {
//                    userView.avatar.zm.setImage(urlStr: u.avatar, placeholder: "def_user_img")
//                    userView.name.text = u.nickname
//                    userView.vip.isHidden = u.serviceProviderLevel == 0
//                } else {
//                    userView.name.text = "暂无"
//                    userView.vip.isHidden = true
//                }
//            }
            
//            let users = resp.nodes.filter({$0.user != nil}).map({$0.user!})
//
//            for u in users {
//                let v = MyTeamUserView()
//                v.name.text = u.nickname
//                v.avatar.zm.setImage(urlStr: u.avatar, placeholder: "def_user_img")
//                v.phone.text = u.phone
//                v.monthOrder.text = "\(u.monthOrder)"
//                v.fans.text = "\(u.fansNum)"
//                v.invite.text = "\(u.inviteNum)"
//                v.totalProfit.text = u.totalProfit.zm.toString(keep: 4)
//                v.todayProfit.text = u.todayProfit.zm.toString(keep: 4)
//                v.monthProfit.text = "\(u.moneyProfit.zm.toString(keep: 4))"
//                v.vipIcon.isHidden = u.serviceProviderLevel == 0
//                stack.addArrangedSubview(v)
//                v.layer.cornerRadius = 12
//                v.masksToBounds = true
//                v.teamBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
//                    router.push("xm://main/Mine/other_fans", context:["id" : u.uid])
//                }).disposed(by: disposeBag)
//
//                v.wechat.isHidden = u.wechatNo.count == 0
//
//                v.onWxClick = { [weak self] in
//                    let v = ZMUtil.loadNibViewFullScreen(nibName: ServiceWx.self)
//                    v.wxLabel.text = u.wechatNo
//                    v.title.text = "微信号"
//                    v.tijkfwx.isHidden = true
//                    APPWindow?.addSubview(v)
//                }
//            }
        }).disposed(by: disposeBag)
    }
    
    func loadMyTeamInfo() {
        loading.showInView(fatherView: view)
        MineAPI.teamInfo(["userId" : ZMAppShareData.share.safeUserId]).rxRequest(type: MineModels.TeamAcModel.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.myTeamInfo.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    func loadMyRecommendInfo() {
        MineAPI.myRecommender.rxRequest(type: [String : String].self).subscribe(onNext:{ [unowned self] resp in
            let json = JSON(resp)
            let avatar = json["avatar"].stringValue
            let nickname = json["nickname"].stringValue
            let wechatCode = json["wechatCode"].stringValue
            let wechatNo = json["wechatNo"].stringValue
            self.img.zm.setImage(urlStr: avatar, placeholder: "def_user_img")
            self.recommendName.text = nickname
            self.wechateCode = wechatCode
            
            if wechatNo.count > 0 {
                self.recommendWx.text = "微信号：" + wechatNo
                self.recommendWxStr = wechatNo
            } else {
                self.recommendWx.isHidden = true
                self.copyButton.isHidden = true
            }
            
            if wechatCode.count > 0 {
                self.codeImg.zm.setImage(urlStr: wechatCode)
                self.wechateCode = wechatCode
            } else {
                self.codeImg.isHidden = true
            }
            
        }).disposed(by: self.disposeBag)
    }
    
    @IBAction func onDirectFans(_ sender: Any) {
        let vc = TeamFansListVC()
        vc.type = 0
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func onIndirectFans(_ sender: Any) {
        let vc = TeamFansListVC()
        vc.type = 1
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func onCopy(_ sender: Any) {
        UIPasteboard.general.string = recommendWxStr
        ZMToast.showToast(title: "已复制")
    }
    
    @objc func onCodeTap() {
        if wechateCode.count > 0 {
            let vc = XMPictureShowVC(imageArray: [wechateCode], index: 0)
            self.present(vc!, animated: true, completion: nil)
        }
    }
    //MARK: --------------------delegate--------------------
}
